﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Guitar.Comet.Message;

namespace Guitar.Comet.Client.SignalR
{
    /// <summary>
    /// SignalR 消息分发器(通知服务端)
    /// </summary>
    public class SignalRMessageDistribution : IMessageDistribution
    {
        private readonly ISignalRClient _signalRClient;

        public SignalRMessageDistribution(ISignalRClient signalRClient)
        {
            _signalRClient = signalRClient;
        }

        /// <summary>
        /// 发送到服务端
        /// </summary>
        /// <param name="message"></param>
        public void SendMessage(MessageEnvelope message)
        {
            string json = JsonConvert.SerializeObject(message);
            try
            {
                // 异步发送至服务端主函数
                _signalRClient.CurrentProxy.Invoke("ServiceHandler", json);

                // if 同步发送至服务端主函数 .Wait();
                if (SuccessActionEvent != null)
                    SuccessActionEvent(this, new CometEventArgs(string.Format("消息:{0}发送成功.", json)));
            }
            catch (Exception ex)
            {
                // 日志
                if (FailActionEvent != null)
                    FailActionEvent(this, new CometEventArgs(string.Format("消息:{0}发送失败,原因:{1},详细请参考日志.", json, ex.Message)));
            }

        }

        public event CometEventHandler<CometEventArgs> FailActionEvent;

        public event CometEventHandler<CometEventArgs> SuccessActionEvent;
    }
}
